import Https from "@/utils/Https";
import { CloseCircleFilled, DownOutlined } from "@ant-design/icons";
import {
  Button,
  DatePicker,
  Dropdown,
  Form,
  Modal,
  Select,
  Space,
  message,
  Spin,
  Segmented,
  Alert,
} from "antd";
import dayjs from "dayjs";
import { FC, useEffect, useState } from "react";
import { lookCard, publishSchedule, weekNameList } from "../../interface";
import styles from "./styles.less";
const OperationItem: FC<any> = (props) => {
  const { defaultTime, onSuccess, updateDimension, onDownImg, dimension } =
    props;
  const [open, setOpen] = useState("");
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [publishForm] = Form.useForm();
  const [copyTime, setCopyTime] = useState<any>({});
  const [isForce, setIsForce] = useState(null);
  const [copyMessage, setCopyMessage] = useState("");
  let customValue = Form.useWatch((values) => values, publishForm);
  //更多操作列表
  const items = [
    {
      label: (
        <a
          onClick={() => {
            setOpen("rest");
          }}
        >
          清空当前课表
        </a>
      ),
      key: "0",
    },
    {
      label: (
        <a
          onClick={() => {
            setOpen("copy");
          }}
        >
          复制当前课表
        </a>
      ),
      key: "1",
    },
    {
      label: (
        <a
          onClick={() => {
            onDownImg();
          }}
        >
          保存当前课表为图片
        </a>
      ),
      key: "3",
      disabled: dimension != "date",
    },
  ];
  const disabledDate = (current) => {
    // Can not select days before today and today
    return current && current < dayjs().endOf("week");
  };
  //复制教室课表
  const saveCopy = async () => {
    await form.validateFields();
    let params = {
      startTimeSlot: defaultTime.startTime + " " + "00:00:00",
      endTimeSlot: defaultTime.endTime + " " + "00:00:00",
      copyToStartTimeSlot: copyTime.startTime,
      copyToEndTimeSlot: copyTime.endTime,
      isForce,
    };
    setLoading(true);
    let res = await Https.post("/course/sched/copy", params, true);
    setLoading(false);
    if (res.code == 200) {
      message.success("操作成功");
      setOpen("");
      onSuccess();
    } else if (res.code == 5121) {
      setIsForce(1);
      setCopyMessage(res.msg);
    } else {
      message.error(res.msg);
    }
  };
  //清空课表
  const restClassRoom = async () => {
    let params = {
      startTimeSlot: defaultTime.startTime + " " + "00:00:00",
      endTimeSlot: defaultTime.endTime + " " + "00:00:00",
    };
    setLoading(true);
    let res = await Https.post("/course/sched/clear", params, true);
    setLoading(false);
    if (res.code == 200) {
      message.success("操作成功");
      setOpen("");
      onSuccess();
    } else {
      message.error(res.msg);
    }
  };
  //获取租户发布配置
  const getPublishInfo = async () => {
    setLoading(true);
    let res = await Https.get("/tenant/schedulePublish/info", {}, true);
    setLoading(false);
    if (res.code == 200 && res.data) {
      publishForm.setFieldsValue({ ...res.data });
    } else {
      message.error(res.msg);
    }
  };
  //修改租户配置
  const updatePublish = async (type, week) => {
    let params = {
      id: customValue.id,
      type,
      week,
    };
    setLoading(true);
    let res = await Https.post(
      "/tenant/schedulePublish/saveOrUpdate",
      params,
      true
    );
    setLoading(false);
    if (res.code == 200) {
      message.success("修改成功");
    } else {
      message.error(res.msg);
    }
  };
  useEffect(() => {
    getPublishInfo();
  }, []);
  useEffect(() => {
    form.resetFields();
    setIsForce(null);
    setCopyMessage("");
  }, [open]);
  return (
    <Spin spinning={loading}>
      <div className={styles.scheduleHeader}>
        <Form
          layout="inline"
          form={publishForm}
          initialValues={{
            type: 1,
            week: 1,
          }}
        >
          <Form.Item label="" name="id" hidden></Form.Item>
          <Form.Item
            label="会员可看课表"
            name="type"
            tooltip={
              <span>
                本周课表：会员只能查看本周课表。
                <br />
                全部课表：会员能查看所有创建的课表。
              </span>
            }
          >
            <Select
              placeholder="请选择"
              style={{ width: "180px" }}
              onChange={(e) => {
                updatePublish(e, 1);
                publishForm.setFieldsValue({ week: 1 });
              }}
            >
              {lookCard &&
                lookCard.map((item) => (
                  <Select.Option key={item.id} value={item.id}>
                    {item.name}
                  </Select.Option>
                ))}
            </Select>
          </Form.Item>
          {customValue && customValue.type == "1" && (
            <Form.Item
              label="发布课表时间"
              name="week"
              tooltip={
                <span>
                  系统会自动在周{weekNameList[customValue.week]}的00:00
                  发布课表(会员可查看已发布的课程表)
                </span>
              }
            >
              <Select
                placeholder="请选择"
                style={{ width: "180px" }}
                onChange={(e) => {
                  updatePublish(customValue.type, e);
                }}
              >
                {publishSchedule &&
                  publishSchedule.map((item) => (
                    <Select.Option key={item.id} value={item.id}>
                      {item.name}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
          )}
          <Form.Item>
            <Dropdown menu={{ items }} trigger={["click"]}>
              <Button type="primary">
                <Space>
                  课表操作
                  <DownOutlined />
                </Space>
              </Button>
            </Dropdown>
          </Form.Item>
          <Form.Item>
            <Segmented
              onChange={() => {
                updateDimension();
              }}
              options={["按日期", "按教室"]}
              block
            />
          </Form.Item>
        </Form>
        <Modal
          title={
            <span>
              <CloseCircleFilled
                style={{ color: "red", fontSize: "20px", marginRight: "10px" }}
              />
              提示
            </span>
          }
          onCancel={() => {
            setOpen("");
          }}
          open={open == "rest"}
          confirmLoading={loading}
          footer={
            <>
              <Button
                onClick={() => {
                  setOpen("");
                }}
              >
                取消
              </Button>
              <Button
                loading={loading}
                style={{ marginLeft: "15px" }}
                type="primary"
                onClick={() => {
                  restClassRoom();
                }}
              >
                清空
              </Button>
            </>
          }
        >
          <p>是否清空当前教室课表?</p>
        </Modal>
        <Modal
          title={`复制当前教室课表 (${defaultTime.startTime} ~ ${defaultTime.endTime})`}
          onCancel={() => {
            setOpen("");
          }}
          open={open == "copy"}
          confirmLoading={loading}
          footer={
            <>
              <Button
                onClick={() => {
                  setOpen("");
                }}
              >
                取消
              </Button>
              <Button
                loading={loading}
                style={{ marginLeft: "15px" }}
                type="primary"
                onClick={() => {
                  saveCopy();
                }}
              >
                {isForce == 1 ? "强制覆盖" : "确定"}
              </Button>
            </>
          }
        >
          {copyMessage && (
            <Alert
              style={{ marginBottom: "24px" }}
              message={copyMessage}
              type="warning"
              showIcon
            />
          )}
          <Form form={form}>
            <Form.Item
              label="选择周"
              name="week"
              rules={[{ required: true, message: "请选择需要复制课表的周" }]}
            >
              <DatePicker
                style={{ width: "200px" }}
                format={`YYYY-MM-DD 第wo`}
                allowClear={false}
                picker="week"
                disabledDate={disabledDate}
                onChange={(date, dateString: string) => {
                  let currentDate = dateString.split(" ")[0];
                  let startTime = dayjs(currentDate)
                    .startOf("week")
                    .format("YYYY-MM-DD HH:mm:ss");
                  let endTime = dayjs(currentDate)
                    .endOf("week")
                    .format("YYYY-MM-DD HH:mm:ss");
                  setCopyTime({ startTime, endTime });
                  setCopyMessage("");
                  setIsForce(null);
                }}
              />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </Spin>
  );
};
export default OperationItem;
